//
//  HelloWorldLayer.mm
//  TestCocosWithBox2
//
//  Created by Nguyen Tan Loc on 8/12/13.
//  Copyright Nguyen Tan Loc 2013. All rights reserved.
//

// Import the interfaces
#import "HelloWorldLayer.h"

// Not included in "cocos2d.h"
#import "CCPhysicsSprite.h"

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
#import "PhysicSystem.h"


enum {
	kTagParentNode = 1,
};


@implementation HelloWorldLayer

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	HelloWorldLayer *layer = [HelloWorldLayer node];
	
	// add layer as a child to scene
	[scene addChild: layer];
	
	// return the scene
	return scene;
}

-(id) init
{
	if( (self=[super init])) {
		
		// enable events
		
		self.touchEnabled = YES;
        
//        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"blocks.png"];
        
        [self initPhysics];
        [self addNewSpriteAtPosition:ccp(100, 100)];
        
		
		[self scheduleUpdate];
	}
	return self;
}



-(void) dealloc
{
//	delete world;
//	world = NULL;
//	
//	delete m_debugDraw;
//	m_debugDraw = NULL;
	
	[super dealloc];
}	
//
//-(void) createMenu
//{
//	// Default font size will be 22 points.
//	[CCMenuItemFont setFontSize:22];
//	
//	// Reset Button
//	CCMenuItemLabel *reset = [CCMenuItemFont itemWithString:@"Reset" block:^(id sender){
//		[[CCDirector sharedDirector] replaceScene: [HelloWorldLayer scene]];
//	}];
//
//	// to avoid a retain-cycle with the menuitem and blocks
//	__block id copy_self = self;
//
//	// Achievement Menu Item using blocks
//	CCMenuItem *itemAchievement = [CCMenuItemFont itemWithString:@"Achievements" block:^(id sender) {
//		
//		
//		GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init];
//		achivementViewController.achievementDelegate = copy_self;
//		
//		AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
//		
//		[[app navController] presentModalViewController:achivementViewController animated:YES];
//		
//		[achivementViewController release];
//	}];
//	
//	// Leaderboard Menu Item using blocks
//	CCMenuItem *itemLeaderboard = [CCMenuItemFont itemWithString:@"Leaderboard" block:^(id sender) {
//		
//		
//		GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init];
//		leaderboardViewController.leaderboardDelegate = copy_self;
//		
//		AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
//		
//		[[app navController] presentModalViewController:leaderboardViewController animated:YES];
//		
//		[leaderboardViewController release];
//	}];
//	
//	CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, reset, nil];
//	
//	[menu alignItemsVertically];
//	
//	CGSize size = [[CCDirector sharedDirector] winSize];
//	[menu setPosition:ccp( size.width/2, size.height/2)];
//	
//	
//	[self addChild: menu z:-1];	
//}
//
-(void) initPhysics
{
//
	CGSize s = [[CCDirector sharedDirector] winSize];
//
//	b2Vec2 gravity;
//	gravity.Set(0.0f, -10.0f);
//	world = new b2World(gravity);
//	
//	
//	// Do we want to let bodies sleep?
//	world->SetAllowSleeping(true);
//	
//	world->SetContinuousPhysics(true);
//	
//	m_debugDraw = new GLESDebugDraw( PTM_RATIO );
//	world->SetDebugDraw(m_debugDraw);
//	
//	uint32 flags = 0;
//	flags += b2Draw::e_shapeBit;
//	//		flags += b2Draw::e_jointBit;
//	//		flags += b2Draw::e_aabbBit;
//	//		flags += b2Draw::e_pairBit;
//	//		flags += b2Draw::e_centerOfMassBit;
//	m_debugDraw->SetFlags(flags);		
//	
//	
//	// Define the ground body.
	b2BodyDef groundBodyDef;
	groundBodyDef.position.Set(0, 0); // bottom-left corner
	
	// Call the body factory which allocates memory for the ground body
	// from a pool and creates the ground box shape (also from a pool).
	// The body is also added to the world.
	b2Body* groundBody = PhysicSystem::getInstance()->mWorld->CreateBody(&groundBodyDef);
	
	// Define the ground box shape.
	b2EdgeShape groundBox;		
	
	// bottom
	
	groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
	groundBody->CreateFixture(&groundBox,0);
	
	// top
	groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO));
	groundBody->CreateFixture(&groundBox,0);
	
	// left
	groundBox.Set(b2Vec2(0,s.height/PTM_RATIO), b2Vec2(0,0));
	groundBody->CreateFixture(&groundBox,0);
	
	// right
	groundBox.Set(b2Vec2(s.width/PTM_RATIO,s.height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
	groundBody->CreateFixture(&groundBox,0);
}
//
-(void) draw
{
	//
	// IMPORTANT:
	// This is only for debug purposes
	// It is recommend to disable it
	//
    
	[super draw];
    PhysicSystem::getInstance()->drawDebug();
    
}
//
-(void) addNewSpriteAtPosition:(CGPoint)p
{
//	CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);
	// Define the dynamic body.
	//Set up a 1m squared box in the physics world
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
	b2Body *body = PhysicSystem::getInstance()->mWorld->CreateBody(&bodyDef);
	
	// Define another box shape for our dynamic body.
	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox(1.f, 1.f);//These are mid points for our 1m box
	
	// Define the dynamic body fixture.
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &dynamicBox;	
	fixtureDef.density = 1.0f;
	fixtureDef.friction = 0.3f;
	body->CreateFixture(&fixtureDef);
	
    CCNode *parent = [self getChildByTag:kTagParentNode];
	
	//We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
	//just randomly picking one of the images
	int idx = (CCRANDOM_0_1() > .5 ? 0:1);
	int idy = (CCRANDOM_0_1() > .5 ? 0:1);
	CCPhysicsSprite *sprite = [CCPhysicsSprite spriteWithFile:@"blocks.png"];
	[self addChild:sprite];
	
	[sprite setPTMRatio:PTM_RATIO];
	[sprite setB2Body:body];
	[sprite setPosition: ccp( p.x, p.y)];
    
    CCSprite *s = [CCSprite spriteWithFile:@"blocks.png"];
    [s setPosition:ccp(300, 300)];
    [self addChild:s];

}
//
-(void) update: (ccTime) dt
{
	//It is recommended that a fixed time step is used with Box2D for stability
	//of the simulation, however, we are using a variable time step here.
	//You need to make an informed choice, the following URL is useful
	//http://gafferongames.com/game-physics/fix-your-timestep/

	// Instruct the world to perform a single step of simulation. It is
	// generally best to keep the time step and iterations fixed.
	PhysicSystem::getInstance()->update(dt);
}
//
//- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
//{
//	//Add a new body/atlas sprite at the touched location
//	for( UITouch *touch in touches ) {
//		CGPoint location = [touch locationInView: [touch view]];
//		
//		location = [[CCDirector sharedDirector] convertToGL: location];
//		
//		[self addNewSpriteAtPosition: location];
//	}
//}
//
//#pragma mark GameKit delegate
//
//-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
//{
//	AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
//	[[app navController] dismissModalViewControllerAnimated:YES];
//}
//
//-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
//{
//	AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
//	[[app navController] dismissModalViewControllerAnimated:YES];
//}

@end
